/*
 * @Date: 2022-04-18 14:39:04
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-04-21 19:17:29
 * @FilePath: \weibovue\src\hooks\usePrevenDefault.ts
 * @Description: 禁用@用户a标签默认
 */
import { onMounted, ref, onUnmounted, nextTick } from "vue";
import router from "../router/index";
const aEl = ref<NodeListOf<Element>>();
const usePrevenDefault = (aClassName: string, type: string = "router") => {
  onMounted(() => {
    nextTick(() => {
      aEl.value = document.querySelectorAll(`.${aClassName}`);
      aEl.value.forEach((val) => {
        let Str = val.getAttribute("href");
        // console.log(val, Str, router);
        val.addEventListener("click", (e: Event) => {
          e.preventDefault();
          if (type === "router") {
            router.push({ path: `${Str}` });
          } else {
            return;
          }
        });
      });
    });
  });
  onUnmounted(() => {
    // console.log("禁用卸载了");

    nextTick(() => {
      aEl.value = document.querySelectorAll(`.${aClassName}`);
      aEl.value.forEach((val) => {
        let Str = val.getAttribute("href");
        // console.log(val, Str, router);
        val.removeEventListener("click", (e: Event) => {
          e.preventDefault();
        });
      });
    });
  });
};
export default usePrevenDefault;
